package com.seanzx.dp.serializer.impl;

import com.seanzx.dp.entity.Column;
import com.seanzx.dp.serializer.ISerializer;

import java.io.FilterInputStream;
import java.io.IOException;

/**
 * UNSIGNED_INT: lower endian, read next 4 bytes as a number. from 0 to 4294967295
 */
public class UnsignedNumberSerializer implements ISerializer {
    private final int length;

    public UnsignedNumberSerializer(int length) {
        this.length = length;
    }

    @Override
    public String deserialize(Column column, FilterInputStream inputStream) throws IOException {
        byte[] bytes = new byte[length];
        inputStream.read(bytes);
        long temp = 0L;
        for (int i = 0; i < bytes.length; i++) {
            temp += (long) (bytes[i] & 0xFF) << (i * 8);
        }
        return String.valueOf(temp);
    }

    @Override
    public byte[] serialize(Column column, String value) {
        byte[] bytes = new byte[length];
        long l = Long.parseLong(value);
        int i = 0;
        while (l > 0) {
            bytes[i] = (byte) (l % 0xFF);
            l /= 0xFF;
        }
        return bytes;
    }

    public static void main(String[] args) {
        byte[] bytes = new byte[4];
        long l = Long.parseLong("65535");
        int i = 0;
        while (l > 0) {
            bytes[i] = (byte) (l % 256);
            l /= 256;
            i++;
        }
        System.out.println(bytes);
    }
}
